# coding:utf-8
from django.contrib.auth import authenticate
from token_auth.models import Token
from userinfo.models import UserProfile
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
import json
from django.http import HttpResponse
from token_auth.utils import json_response, token_required
from hlr_django import settings


@csrf_exempt
def token(request):
    # 登录
    if request.method == 'GET':
        return login(request)


    # 登出
    elif request.method == 'DELETE':
        return logout(request)
    elif request.method == 'PUT':
        return validate(request)


@token_required
def validate(request):

    return json_response({})

@token_required
def logout(request):

    request.token.delete()

    return json_response({})

def login(request):
    phone = request.GET.get('phone', None)
    password = request.GET.get('password', None)
    host = request.get_host()
    if phone is not None and password is not None:
        user_profile = UserProfile.objects.filter(phone=phone)
        if len(user_profile) == 0:
            return json_response({'error':'user do not  exist'},status=401)
        username = user_profile[0].user.username

        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                
                token, created = Token.objects.get_or_create(user=user)
                user_profile = user.get_profile()
                sign_text = user_profile.sign

                if sign_text is None:
                    sign_text = '您什么都没留下呢'
                avatar = 'http://'+host+settings.MEDIA_URL+str(user_profile.avatar)

                return json_response({
                    'token': token.token,
                    'nickname': user_profile.nick_name,
                    'sign':sign_text,
                    'gender':user_profile.gender,
                    'avatar':avatar,
                    'phone':user_profile.phone,
                    'height':user_profile.height+'cm'
                })
            else:

                return json_response({ 'error': 'Invalid User'
                                         }, status=401)
        else:
            return json_response({'error': 'Invalid Username/Password'
                                }, status=401)
    else:
        return json_response({'error': 'Invalid Data'
                            }, status=401)



